"""
/file pkPlaylist.py
/authors guillaume
/date 12-08-2013
"""

from pkPlayback import pkPlayback
from random import shuffle


class pkPlaylist():
	""" Controls over the playlist """

	_PREVIOUS_THRESHOLD = 4000 # in milli-secconds

	def __init__(self, songs_list = [], parent=None):

		self._playback = pkPlayback(parent)
		self._index = 0
		self._songs_list = songs_list
		self.update_queue()

		self._repeat_mode = False


	def next(self):
		""" Skip to next song in the Phonon MediaObject's queue """		
		self.index += 1


	def previous(self):
		"""
		Returns to the beginning of the current source, or to the previous
		one if the song started less than _PREVIOUS_THRESHOLD ago
		"""
		elapsed_time = self._playback.get_elapsed_time()
		if (elapsed_time < pkPlaylist._PREVIOUS_THRESHOLD):
			self.index -= 1
		else:
			self._playback.seek(0)


	def go_to_song(self, song_index):
		"""
		start the song at the specified index
		song_position: songPositionInStack(song_group, song_index_in_group)
		"""
		if (song_index < len(self._songs_list) and song_index >= 0):
			self._index = song_index
			self.update_queue()


	def update_queue(self):
		""" Update the playback queue """
		self._playback.clear()
		new_queue = self._songs_list[self._index:]
		self._playback.set_queue(new_queue)


	def get_playing_song(self):
		""" Return the song currently playing """
		return self._playback.get_playing_song()


	def _get_index(self):
		return self._index


	def _set_index(self):
		"""
		Verify if the index is between 0 and the song_list lenght and correct
		it if not dependind of whether or not the repeat_mode is enabled
		"""
		if (self._repeat_mode):
			if (self._index < 0):
				self._index = len(self._songs_list) - 1
			elif (self._index >= len(self._songs_list)):
				self._index = 0
			self.update_queue()
		else:
			if (self._index < 0):
				self._index = 0
				self._playback.seek(0)
			elif (self._index >= len(self._songs_list)):
				self._index = len(self._songs_list) - 1
			else:
				self.update_queue()

	index = property(_get_index, _set_index)


	def _set_repeat_mode(self, is_repeat_on):
		self._repeat_mode = is_repeat_on


	def _get_repeat_mode(self):
		return self._repeat_mode

	repeat_mode = property(_get_repeat_mode, _set_repeat_mode)

	
	def shake_list(self):
		tmp_list = []
		tmp_list = self._song_list[(self.index+1):]
		while True:
			try:
				del self._song_list[self.index+1]
			except IndexError:
				break
		shuffle(tmp_list)
		self._song_list += tmp_list
		return self._song_list
